/****************************************************************
 ** Product  :   HP Subscriber Network Application Policy
 ** Module   :   gr-manager
 ** Date: Apr 10, 2015               
 ** Author: Chen Zhenhua
 ** (C) Copyright 2015, Hewlett-Packard Company, All Rights Reserved.
 ** This software is the proprietary information of HP, Inc.  
 ** Use is subject to license terms.
 *****************************************************************
 ** Description:   
 **    Get Deployment site status.
 **    
 ****************************************************************/
package com.hp.snap.gr.action.impl;

import com.hp.snap.gr.exception.ActionException;
import com.hp.snap.gr.model.DeployStatus;
import com.hp.snap.gr.model.jaxb.ActionType;
import com.hp.snap.gr.model.jaxb.GeneralActionType;
import com.hp.snap.gr.model.jaxb.ParameterType;
import com.hp.snap.gr.utils.Constants;
import com.hp.snap.gr.utils.JSONUtils;
import com.hp.snap.gr.utils.SSHTools;
import com.hp.snap.gr.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.List;
import java.util.Map;

/**
 * Get Deployment site status. The Deployment is local deployment site or remote deployment site. Which can be specified
 * in the action configuration parameter. Construct the DeployStatus object,which include DeployName, DeployRole, GR
 * Status, session server status and biz service status info. And then the DeployStatus object save to
 * actionPlanOutputs("REMOTE_DEPLOY_STATUS").
 * 
 * 
 * There are two parameters can be configured in the action: Shell and Remote.
 * 
 * Shell: get session server status shell script. Remote: is remote or local session sever, optional value: true or
 * false.
 * 
 * Action output: REMOTE_DEPLOY_STATUS: the deployment site status.
 * 
 * <P>
 * Version: 3.3 <br>
 * Author: Chen Zhenhua Date: Apr 10, 2015
 * 
 * </P>
 * 
 **/
public class GetDeploymentStatusActionHandler extends AbstractActionHandler {

    private final static String SS_STATUS_RESULT_PREFIX = "{\"results\"";
    private static Logger logger = LoggerFactory.getLogger(GetDeploymentStatusActionHandler.class);

    @Override
    public void execute(ActionType action,
                        Map<String, Object> actionPlanInputs,
                        Map<String, Object> actionPlanOutputs) throws ActionException {

        GeneralActionType actionType = (GeneralActionType) action;
        List<ParameterType> parameterTypes = actionType.getParameter();
        Map<String, String> parameterMap = Utils.contructParamMap(parameterTypes);

        String shellscript = parameterMap.get("Shell");
        String kernelConfigPath = parameterMap.get("GLOBAL_KERNEL_CONFIG_NODE");
        if (logger.isDebugEnabled()) {
            logger.debug("The shell script is:{}", Utils.maskEIUMPasswd(shellscript));
        }
        boolean remote = parameterMap.get("Remote") != null ? Boolean.parseBoolean(parameterMap.get("Remote")) : false;
        String runSiteName = Utils.getConfigurationValue(Constants.CFG_GRL_DEPLOY_NAME);
        if (remote)
            runSiteName = Utils.getCorrespondSiteName(runSiteName);

        String grIP = Utils.getGRHostIP(runSiteName);
        String sshUser = Utils.getConfigurationValue(Constants.CFG_GRG_ROOT + "/" + runSiteName, Constants.CFG_GRG_SITE_SSH_USER);
        String result;
        SSHTools ssh = new SSHTools(sshUser, Constants.SSH_PATH + File.separator + Constants.SSH_KEY_FILE);
        try {
            result = ssh.executeRemoteShell(false, shellscript, grIP);
        } catch (Exception e) {
            throw new ActionException(e.getMessage(), e.getCause());
        }
        int status = ssh.getExitStatusOfCommandResult(result);
        String resultStr = ssh.getCommandOutput(result);
        if (status != 0) {
            logger.error("execute the getting {} session server status shell script failed!", runSiteName);
            throw new ActionException("execute the getting " + runSiteName + " session server status shell script failed!");

        }
        String ssStatusStr = "";
        try {
            LineNumberReader r = new LineNumberReader(new StringReader(
                    resultStr));
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                if (line.startsWith(SS_STATUS_RESULT_PREFIX)) {
                    ssStatusStr = line;
                    break;
                }
            }
        } catch (IOException e) {
            throw new ActionException(
                    "handle the session server status result failed!",
                    e.getCause());

        }
        if (logger.isDebugEnabled()) {
            logger.debug("session server status json string is:{}", ssStatusStr);
        }

        DeployStatus deployStatus = JSONUtils.getDeployStatus(ssStatusStr, remote, kernelConfigPath);


        actionPlanOutputs.put(Constants.REMOTE_DEPLOY_STATUS, deployStatus);

    }

}
